package com.hotau.location;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;

import com.hotau.HotauActivity;
import com.hotau.NavigationActivity;
import com.hotau.R;
import com.hotau.framework.FooterVisible;
import com.hotau.framework.SearchBarVisible;
import com.hotau.member.LoginFragment;
import com.hotau.member.RegisterFragment;
import com.hotau.member.service.MemberService;
import com.hotau.push.PushService;
import com.hotau.ui.Gallery;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpUtil;
import com.hotau.util.PreferencesUtils;

/**
 * 聚合界面
 * 
 * @author Cruise
 * @data 2013-11-10
 * @version 1.0
 *          <ul>
 *          <li>1.0 创建</li>
 *          </ul>
 */
public class TogetherFragment extends Fragment implements
		OnItemSelectedListener, OnItemClickListener, OnClickListener,
		FooterVisible, SearchBarVisible {

	public static final String TAG = "TogetherFragment";

	private Gallery mTogetherGallery;
	// private PageIndicatorView mPageView;
	private ImageAdapter mAdapter;
	private TabHost categoryTabHost;
	private FrameLayout tabcontent;
	
	private LocalActivityManager localAcManager;
	private RadioGroup radioGroup;
	
	private static final int[] mPicture = new int[] { R.drawable.banner01,
			R.drawable.banner02, R.drawable.banner03, R.drawable.banner04,
			R.drawable.banner05, R.drawable.banner06 };

	Intent getMainActivity = null;

	public static int galleryImageHeight = 90;
	public static int galleryImageWidth = 100;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// 启动推送服务
		String receive = PreferencesUtils.getReceive(getActivity());
		if ("1".equals(receive) || HttpUtil.hasInternet(getActivity())) {
			Intent service = new Intent(getActivity(), PushService.class);
			getActivity().stopService(service);
			getActivity().startService(service);
		}
		
		localAcManager = new LocalActivityManager(getActivity(), true);
		localAcManager.dispatchCreate(savedInstanceState);
		
		initAllWidget();
		initAllEvent();
		initAllData();

		mTogetherGallery = (Gallery) getActivity().findViewById(
				R.id.pre_together_gallery);

		mTogetherGallery.setOnItemClickListener(this);
		mTogetherGallery.setOnItemSelectedListener(this);
		mTogetherGallery.setLongClickable(false);
		// mPageView.setTotalPage(mPicture.length);

		mAdapter = new ImageAdapter(getActivity());
		mTogetherGallery.setAdapter(mAdapter);
		if (mPicture != null && mPicture.length > 1) {
			mTogetherGallery.setSelection(1);
		}

		mAdapter.notifyDataSetChanged();

		// // 如果接受到通知，跳转到订单首页
		// HNAPAYActivity hnapayActivity = (HNAPAYActivity) getActivity();
		// if (hnapayActivity.isReceivedNotificationOrder()) {
		// hnapayActivity.pushFragment("订单查询", new OrderManagementFragment());
		// hnapayActivity.setReceivedNotificationOrder(false);
		// }

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.location_together, container, false);
	}

	class ImageAdapter extends BaseAdapter {
		Context context;

		public ImageAdapter(Context ctx) {
			this.context = ctx;
		}

		@Override
		public int getCount() {
			return mPicture.length;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings("deprecation")
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = new ImageView(context);
			LinearLayout layout = new LinearLayout(context);
			int width = (int) (galleryImageWidth * HotauActivity.galleryImageRate);
			int height = (int) (galleryImageHeight * HotauActivity.galleryImageRate);
			layout.setLayoutParams(new Gallery.LayoutParams(width, height));
			layout.addView(imageView);
			imageView.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			imageView.setBackgroundResource(mPicture[position]);
			return layout;
		}
	}

	public void onClick(View v) {

		if (!HttpUtil.hasInternet(getActivity())) {
			DialogUtil.showDialog(getActivity(), "",
					getString(R.string.connection_fail));
			return;
		}
	}

	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		categoryTabHost = (TabHost) getActivity().findViewById(android.R.id.tabhost);
		radioGroup = (RadioGroup) getActivity().findViewById(R.id.radiogroup);
		tabcontent = (FrameLayout) getActivity().findViewById(android.R.id.tabcontent);
	}

	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch(checkedId){
					case R.id.food_radio:
						Log.i(TAG, "tab [food] is selected.");
						categoryTabHost.setCurrentTabByTag("food");
						break;
					case R.id.drink_radio:
						Log.i(TAG, "tab [drink] is selected.");
						categoryTabHost.setCurrentTabByTag("drink");
						break;
					case R.id.fruit_radio:
						Log.i(TAG, "tab [fruit] is selected.");
						categoryTabHost.setCurrentTabByTag("fruit");
						break;
					case R.id.cuisine_radio:
						Log.i(TAG, "tab [cuisine] is selected.");
						categoryTabHost.setCurrentTabByTag("cuisine");
						break;
					case R.id.furniture_radio:
						Log.i(TAG, "tab [furniture] is selected.");
						categoryTabHost.setCurrentTabByTag("furniture");
						break;
					case R.id.clothes_radio:
						Log.i(TAG, "tab [clothes] is selected.");
						categoryTabHost.setCurrentTabByTag("clothes");
						break;
					case R.id.others_radio:
						Log.i(TAG, "tab [others] is selected.");
						categoryTabHost.setCurrentTabByTag("others");
						break;
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	public void initAllData() {
		//如果通过findViewById得到TabHost 一定要调用 TabHost.setup();
		categoryTabHost.setup(localAcManager); 
		
		LinearLayout.LayoutParams leftLayoutParams = (LinearLayout.LayoutParams) tabcontent
				.getLayoutParams();
		leftLayoutParams.height = HotauActivity.window_height -  
				NavigationActivity.NAVBAR_HEIGHT - NavigationActivity.FOOTER_HEIGHT;
		tabcontent.setLayoutParams(leftLayoutParams);
		
		Intent tabIntent1 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent1.putExtra("tabIndicator", 1);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("food")
				.setIndicator("美食")
				.setContent(tabIntent1));
		
		Intent tabIntent2 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent2.putExtra("tabIndicator", 2);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("drink")
				.setIndicator("美饮")
				.setContent(tabIntent2));
		
		Intent tabIntent3 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent3.putExtra("tabIndicator", 3);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("fruit")
				.setIndicator("果蔬")
				.setContent(tabIntent3));
		
		Intent tabIntent4 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent4.putExtra("tabIndicator", 4);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("cuisine")
				.setIndicator("烹饪")
				.setContent(tabIntent4));
		
		Intent tabIntent5 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent5.putExtra("tabIndicator", 5);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("furniture")
				.setIndicator("家具")
				.setContent(tabIntent5));
		
		Intent tabIntent6 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent6.putExtra("tabIndicator", 6);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("clothes")
				.setIndicator("服装")
				.setContent(tabIntent6));
		
		Intent tabIntent7 = new Intent(getActivity(), HomeProductActivity.class);
		tabIntent7.putExtra("tabIndicator", 7);
		categoryTabHost.addTab(categoryTabHost
				.newTabSpec("others")
				.setIndicator("其它")
				.setContent(tabIntent7));
		
		categoryTabHost.setCurrentTabByTag("food");
	}

	public void processRightBtn(final Context context, Button rightBtn) {
		if (MemberService.isLogin(context)) {
			Log.d("mytag", "TogetherFragment processRightBtn已经登录");
			rightBtn.setText("注销");
			rightBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					Dialog dialog = new AlertDialog.Builder(context)
							.setTitle("提示")
							.setMessage("确定注销?")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											dialog.dismiss();
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											MemberService.logout(context);
											dialog.dismiss();

											// 注销成功提示
											DialogUtil.showDialog(context, "", "注销成功!");
											HotauActivity csmbpActivity = (HotauActivity) context;
											csmbpActivity.toHome();
										}
									}).create();
					dialog.show();

				}
			});
		} else {
			Log.d("mytag", "未登录");
			rightBtn.setText("登录");
			rightBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					if (!HttpUtil.hasInternet(getActivity())) {
						DialogUtil.showDialog(getActivity(), "",
								getString(R.string.connection_fail));
						return;
					}

					HotauActivity csmbpActivity = (HotauActivity) getActivity();
					csmbpActivity.pushFragment("登录", new LoginFragment());
				}
			});
		}

	}

	public void processLeftBtn(final Context context, Button leftBtn) {
		HotauActivity csmbpActivity = (HotauActivity) context;
		if (MemberService.isLogin(context)) {
			Log.d("mytag", "TogetherFragment processLeftBtn已经登录");
			csmbpActivity.leftButton.setVisibility(View.GONE);
			csmbpActivity.leftText.setVisibility(View.VISIBLE);
			csmbpActivity.leftText.setText("");
		} else {
			csmbpActivity.leftText.setVisibility(View.GONE);
			leftBtn.setText("注册");
			leftBtn.setBackgroundResource(R.drawable.btn_style);
			leftBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					if (!HttpUtil.hasInternet(getActivity())) {
						DialogUtil.showDialog(getActivity(), "",
								getString(R.string.connection_fail));
						return;
					}

					HotauActivity csmbpActivity = (HotauActivity) context;
					csmbpActivity.pushFragment("注册", new RegisterFragment());
				}
			});
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d("mytag", "onResume... ");
		if (MemberService.isLogin(getActivity())) {
			Log.d("mytag", "onResume... login");
			HotauActivity csmbpActivity = (HotauActivity) getActivity();
			csmbpActivity.leftButton.setVisibility(View.GONE);
			csmbpActivity.leftText.setVisibility(View.VISIBLE);
			csmbpActivity.leftText.setText("");
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		HotauActivity csmbpActivity = (HotauActivity) getActivity();
		csmbpActivity.leftText.setVisibility(View.GONE);
		csmbpActivity.leftButton.setVisibility(View.VISIBLE);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// mPageView.setCurrentPage(position);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		// mPageView.setCurrentPage(position);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}
}
